import React, { useEffect, useState } from 'react'
import Panner from '../../../components/Panner'
import { Table, Pagination, Space, Button, Modal, Form, Input, Select, message } from 'antd';
import { userList, usersDel, usersEdit } from '../../../api/account'
import dayjs from 'dayjs';
import { useNavigate } from 'react-router-dom';
const { Option } = Select;

export default function List() {
  const navigate = useNavigate()
  const columns = [
    {
      title: '账号',
      dataIndex: 'account'
    },
    {
      title: '用户组',
      dataIndex: 'userGroup'
    },
    {
      title: '创建时间',
      dataIndex: 'createTime'
    },
    {
      title: '操作',
      dataIndex: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button type='primary' style={{ fontSize: 13 }} onClick={() => showModal(record)}>编辑</Button>
          <Button type='primary' danger style={{ fontSize: 13 }} onClick={() => del(record)}>删除</Button>
        </Space>
      ),
    },
  ];
  const layout = {
    labelCol: {
      span: 6,
    },
    wrapperCol: {
      span: 16,
    },
  };
  const [form] = Form.useForm();
  const [currentPage, setCurrentPage] = useState(1)
  const [pageSize, setPageSize] = useState(5)
  const [total, setTotal] = useState()
  const [data, setData] = useState([])
  const [user, setUser] = useState(
    {
      id: '',
      account: '',
      userGroup: ''
    }
  )
  // 分页改变
  const onPageChange = (page, pageSize) => {
    setCurrentPage(page);
    setPageSize(pageSize);
  };
  // 拿到所选行的数据
  const rowSelection = {
    onChange: (selectedRowKeys, selectedRows) => {
      // console.log(selectedRowKeys);
      // console.log(selectedRows);
    }
  };
  // 对话框
  const [isModalOpen, setIsModalOpen] = useState(false);
  // 点击修改，拿到当前行的数据
  const showModal = (e) => {
    setIsModalOpen(true);
    // 修改id和account
    setUser({
      ...user,
      id: e.key,
      account: e.account,
      userGroup: e.userGroup
    })
  };
  // 确定后修改账号信息
  const handleOk = () => {
    edit(user)
  };
  // 取消
  const handleCancel = () => {
    setIsModalOpen(false);
  };
  const onGenderChange = (e) => {
    setUser({
      ...user,
      userGroup: e
    })
  }
  // 获取账号列表请求
  const accountList = async (value) => {
    const res = await userList(value)
    setTotal(res.data.total)
    const data = res.data.data
    const mapData = data.map(item => ({
      key: item.id,
      account: item.account,
      userGroup: item.userGroup,
      createTime: dayjs(item.ctime).format('YYYY-MM-DD')
    }))
    setData(mapData)
  }
  // 修改账号信息请求
  const edit = async (value) => {
    const res = await usersEdit(value)
    const { code, msg } = res.data
    if (code == 0) {
      setIsModalOpen(false);
      // 重新渲染数据列表
      await accountList({ currentPage, pageSize })
      message.open({
        type: 'success',
        content: msg,
      })
    }
  }
  // 删除账号
  const del = async (value) => {
    const userId = JSON.parse(localStorage.getItem('user')).id
    const id = value.key
    const res = await usersDel({ id })
    const { code, msg } = res.data
    await accountList({ currentPage, pageSize })
    if (code == 0) {
      message.open({
        type: 'success',
        content: msg,
      })
      if (userId == id) {
        navigate('/login')
        message.open({
          type: 'success',
          content: '请重新登陆',
        })
      }
    }
  }
  useEffect(() => {
    accountList({ currentPage, pageSize })
  }, [currentPage, pageSize])
  return (
    <>
      <Panner>
        <div slot='title'>账号列表</div>
        <Table
          rowSelection={{
            ...rowSelection,
          }}
          columns={columns}
          dataSource={data}
          pagination={false}
          style={{ marginBottom: 5 }}
        />
        <Modal title="修改账号信息"
          open={isModalOpen}
          onOk={handleOk}
          onCancel={handleCancel}>
          <Form
            {...layout}
            form={form}
            name="control-hooks"
            style={{
              maxWidth: 400,
            }}
          >
            <Form.Item
              name="account"
              label="账号名"
              initialValue={user.account}
            >
              <Input />
            </Form.Item>
            <Form.Item
              name="userGroup"
              label="用户组"
              initialValue={user.userGroup}
            >
              <Select
                allowClear
                onChange={onGenderChange}
              >
                <Option value="超级管理员">超级管理员</Option>
                <Option value="普通管理员">普通管理员</Option>
              </Select>
            </Form.Item>
          </Form>
        </Modal>
        <Pagination
          total={total}
          defaultPageSize={5}
          pageSizeOptions={[5, 10, 20, 30]}
          showSizeChanger
          showQuickJumper
          showTotal={(total) => `共 ${total} 条`}
          onChange={onPageChange}
          defaultCurrent={currentPage}
          style={{ marginTop: 5 }}
        />
      </Panner>
    </>
  )
}
